package postgres

import (
	"context"
	"gorm.io/gorm"
	"manager/errors"
	"manager/model"
	"manager/model/entity"
)

var PromotionalImage = &promotionalImage{}

type promotionalImage struct{}

// Create 创建
func (a *promotionalImage) Create(ctx context.Context, m *entity.PromotionalImage) (int64, error) {
	err := GetDB(ctx).Create(m).Error
	return m.Id, err
}

// Find 查找详情
func (a *promotionalImage) Find(ctx context.Context, in *model.PromotionalImageInfoRequest) (*entity.PromotionalImage, error) {
	e := &entity.PromotionalImage{}

	q := GetDB(ctx).Model(&entity.PromotionalImage{})

	if in.Id > 0 {
		err := q.First(&e, in.Id).Error
		return e, err
	}

	count := 0

	if in.Name != nil {

		q = q.Where("name like ?", in.Name)

		count++
	}

	if in.Desc != nil {

		q = q.Where("desc like ?", in.Desc)

		count++
	}

	if in.ImageUrl != nil {

		q = q.Where("image_url like ?", in.ImageUrl)

		count++
	}

	if in.Weight != nil {

		q = q.Where("weight = ?", in.Weight)

		count++
	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

		count++
	}

	if count == 0 {
		return e, errors.New("condition illegal")
	}

	err := q.First(&e).Error
	return e, err
}

// Update 更新
func (a *promotionalImage) Update(ctx context.Context, id int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.PromotionalImage{}).Where("id = ?", id).Updates(dict).Error
}

// Delete 删除
func (a *promotionalImage) Delete(ctx context.Context, id int64) error {
	return GetDB(ctx).Delete(&entity.PromotionalImage{}, id).Error
}

// List 列表查询
func (a *promotionalImage) List(ctx context.Context, in *model.PromotionalImageListRequest) (int, []*entity.PromotionalImage, error) {
	var (
		q                 = GetDB(ctx).Model(&entity.PromotionalImage{})
		err               error
		total             int64
		promotionalImages []*entity.PromotionalImage
	)

	if in.Name != nil {

		q = q.Where("name like ?", in.Name)

	}

	if in.Desc != nil {

		q = q.Where("desc like ?", in.Desc)

	}

	if in.ImageUrl != nil {

		q = q.Where("image_url like ?", in.ImageUrl)

	}

	if in.Weight != nil {

		q = q.Where("weight = ?", in.Weight)

	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

	}

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Order("created_at desc").Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&promotionalImages).Error; err != nil {
		return 0, nil, err
	}
	return int(total), promotionalImages, nil
}

// ExecTransaction db事务执行
func (a *promotionalImage) ExecTransaction(ctx context.Context, callback func(ctx context.Context) error) error {
	return GetDB(ctx).Transaction(func(tx *gorm.DB) error {
		ctx = context.WithValue(ctx, DBCONTEXTKEY, tx)
		return callback(ctx)
	})
}
